package org.snusmumr.android.media.dialog;

import java.util.List;

import org.snusmumr.android.media.Constants;
import org.snusmumr.android.media.R;
import org.snusmumr.android.media.bean.LabelModel;
import org.snusmumr.android.media.data.DatabaseManager;
import org.snusmumr.android.media.data.adapter.CheckedLabelCursorAdapter;

import android.app.Dialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;

public class SelectLabelDialog extends Dialog {
	
	public interface OnLabelsSelectListener {
		public void onLabelsSelected(List<LabelModel> selectedLabels);
	}
	
	private ListView lablesView;
	private SQLiteDatabase mDatabase;
	private DatabaseManager mDbManager;
	private Cursor cursor;
	
	private OnLabelsSelectListener onLabelsSelectListener;

	public SelectLabelDialog(Context context, OnLabelsSelectListener onLabelsSelectListener) {
		super(context);
		this.onLabelsSelectListener = onLabelsSelectListener;
	}

	public SelectLabelDialog(Context context, int theme, OnLabelsSelectListener onLabelsSelectListener) {
		super(context, theme);
		this.onLabelsSelectListener = onLabelsSelectListener;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setTitle(R.string.select_lables_dlg_title);
		setContentView(R.layout.select_label_dlg);
		lablesView = new ListView(this.getContext());
		lablesView.setId(android.R.id.list);
		LinearLayout scroll = (LinearLayout) findViewById(R.id.select_label_scroll);
		scroll.addView(lablesView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        
        mDbManager = new DatabaseManager(this.getContext(), null);
        mDatabase = mDbManager.getReadableDatabase();
        cursor = mDatabase.query(Constants.DB_TABLE_LABEL, 
				Constants.DB_COLUMNS_LABEL, 
				null, null, null, null, "name asc");
        final CheckedLabelCursorAdapter adapter = new CheckedLabelCursorAdapter(this.getContext(), cursor);
        lablesView.setAdapter(adapter);
        
        Button ok = (Button) findViewById(R.id.btn_select_label_ok);
        ok.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				onLabelsSelectListener.onLabelsSelected(adapter.getSelectedLabels());
				dismiss();
			}
		});
        Button cancel = (Button) findViewById(R.id.btn_select_label_cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dismiss();
			}
		});
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		cursor.close();
		mDatabase.close();
	}
		
}
